package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentCallBackService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.article.pojos.ApUser;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.treadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentCallBackServiceImpl implements CommentCallBackService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;







    //展示回复评论的评论
    @Override
    public ResponseResult callBackDisplay(CommentRepayDTO dto) {

        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);

        if (dto.getMinDate()==null) {
            dto.setMinDate(new Date());
        }

        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate())).limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        ApUser user = AppThreadLocalUtils.getUser();

        if (user == null || apCommentRepays == null || apCommentRepays.size() == 0) {
            return ResponseResult.okResult(apCommentRepays);
        }

        List<String> commentRepayIds = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());

        Query query1 = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").in(commentRepayIds));

        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);



        if(apCommentRepayLikes !=null &&apCommentRepayLikes.size()>0){

            List<ApCommentRepayVO> apCommentRepayVoList = new ArrayList<>();

            List<String> Ids = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());


            for (ApCommentRepay apCommentRepay : apCommentRepays) {

                ApCommentRepayVO apCommentRepayVo = new ApCommentRepayVO();
                BeanUtils.copyProperties(apCommentRepay,apCommentRepayVo);
                if(Ids.contains(apCommentRepay.getId())){
                    apCommentRepayVo.setOperation((short)0);
                }
                apCommentRepayVoList.add(apCommentRepayVo);
            }
            return ResponseResult.okResult(apCommentRepayVoList);
        }


















        return ResponseResult.okResult(apCommentRepays);
    }





    //保存回复评论
    @Autowired
    GreenTextScan greenTextScan;
    @Override
    public ResponseResult callBackSave(CommentRepaySaveDTO dto) {
        //阿里云文本审核
        handleText(dto.getContent());

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<ApUser> userResult = userFeign.findUserById(user.getId());
        if(userResult.getCode()!=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        user = userResult.getData();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());

        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();

    }



    //点赞评论的实现
    @Override
    public ResponseResult callBackLike(CommentRepayLikeDTO dto) {

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"需要登录");
        }


        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if(apCommentRepay == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
        }

        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId()));

        ApCommentRepayLike repayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);

        if (dto.getOperation() == 0) {
            if(repayLike != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
            }

            //保存
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);


            ApCommentRepayLike apCommentLike = new ApCommentRepayLike();

            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentRepayId(apCommentRepay.getId());
            apCommentLike.setOperation(dto.getOperation());

            mongoTemplate.save(apCommentLike);
        } else {

            apCommentRepay.setLikes(apCommentRepay.getLikes() - 1);
            mongoTemplate.save(apCommentRepay);

            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);

    }







    //阿里云的检查方法
    private void handleText(String content) {

        try {
            Map map = greenTextScan.greenTextScan(content);
            //有返回结果
            String suggestion = (String) map.get("suggestion");

            switch (suggestion) {
                case "review":
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文本中有违规内容，审核失败");
                    break;
                case "block":
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文本中有违规内容，审核失败");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文本中有违规内容，审核失败");
        }
    }
}
